// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.SupplierOrderProduct;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.ProductMapper;
import com.fowo.api.mapper.SupplierOrderProductMapper;
import com.fowo.api.model.product.ProductItemVo;
import com.fowo.api.model.product.ProductSearchParamPo;
import com.fowo.api.model.supplier.order.product.SupplierOrderProductExcelPo;
import com.fowo.api.model.supplier.order.product.SupplierOrderProductImportPo;
import com.fowo.api.model.supplier.order.product.SupplierOrderProductItemVo;
import com.fowo.api.model.supplier.order.product.SupplierOrderProductItemVoPages;
import com.fowo.api.model.supplier.order.product.SupplierOrderProductSearchParamPo;
import com.fowo.api.model.supplier.order.product.SupplierOrderProductVo;
import com.fowo.api.model.supplier.order.product.constant.SupplierOrderProductBusinessIdentEnums;
import com.fowo.api.service.SupplierOrderProductService;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 供应商订单子表 服务实现类
 * @author 蜂窝蜜造平台 配置人：周计鑫，任凯
 */
@Service
@Slf4j
@DataObjectType(SupplierOrderProduct.class)
@DS("ds24")
public class SupplierOrderProductServiceImpl
  extends ServiceImpl<SupplierOrderProductMapper, SupplierOrderProduct>
  implements SupplierOrderProductService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("parentSupplierOrderSupplierOrder", "so.`supplier_order`");
      put("productIdName", "p.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected SupplierOrderProductService self;

  @Resource
  protected ProductMapper productMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Resource
  protected Validator validator;

  /**
   * 创建供应商订单子表
   * @param model 供应商订单子表
   * @return 新数据的主键
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(SupplierOrderProductVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    SupplierOrderProduct entity = new SupplierOrderProduct();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.save(entity)) {
      return entity.getId();
    }
    throw new Exception("供应商订单子表保存失败");
  }

  /**
   * 批量更新 供应商订单 下属数据
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void saveAllByParentSupplierOrder(
    Long parentSupplierOrder,
    List<SupplierOrderProductItemVo> list
  ) throws Exception {
    for (SupplierOrderProductItemVo itemVo : list) {
      if (
        itemVo.getId() != null &&
        itemVo.getDelFlag() != null &&
        itemVo.getDelFlag()
      ) {
        // 删除处理
        this.delete(itemVo.getId());
        continue;
      }
      SupplierOrderProduct item = new SupplierOrderProduct();
      BeanUtils.copyProperties(itemVo, item);
      if (item.getParentSupplierOrder() == null) {
        item.setId(null);
        item.setParentSupplierOrder(parentSupplierOrder);
      }
      if (item.getId() == null) {
        this.save(item);
      } else {
        this.updateById(item);
      }
    }
  }

  /**
   * 返回 供应商订单 下属多级分页
   */
  @Override
  public Map<String, Page<SupplierOrderProductItemVoPages>> pagesByParentSupplierOrder(
    SupplierOrderProductSearchParamPo search
  ) {
    search.setDisableDataPremissions(true);
    List<SupplierOrderProductItemVoPages> listMap =
      baseMapper.selectPagesByParentSupplierOrder(search);
    Map<Long, List<SupplierOrderProductItemVoPages>> pageMap = listMap
      .stream()
      .collect(
        Collectors.groupingBy(
          SupplierOrderProductItemVoPages::getParentSupplierOrder
        )
      );
    Map<String, Page<SupplierOrderProductItemVoPages>> result = new HashMap<>();
    for (Map.Entry<Long, List<SupplierOrderProductItemVoPages>> listEntry : pageMap.entrySet()) {
      Page<SupplierOrderProductItemVoPages> page = new Page<>(
        1,
        search.getPageSize(),
        listEntry.getValue().get(0).getPartRows()
      );
      page.setRecords(listEntry.getValue());
      result.put(listEntry.getKey().toString(), page);
    }
    return result;
  }

  /**
   * 更新供应商订单子表
   * @param model 供应商订单子表
   * @return 更新是否成功
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(SupplierOrderProductVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    SupplierOrderProduct entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("供应商订单子表不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      return true;
    }
    return false;
  }/**
   * 更新供应商订单子表（带空值）
   * @param model 供应商订单子表
   * @return 更新是否成功
   */

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(SupplierOrderProductVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    SupplierOrderProduct entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("供应商订单子表不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(
        SupplierOrderProduct::getParentSupplierOrder,
        model.getParentSupplierOrder()
      )
      .set(SupplierOrderProduct::getSupplierOrderId, model.getSupplierOrderId())
      .set(SupplierOrderProduct::getBusinessIdent, model.getBusinessIdent())
      .set(SupplierOrderProduct::getProductId, model.getProductId())
      .set(SupplierOrderProduct::getLastUpdateTime, model.getLastUpdateTime())
      .set(SupplierOrderProduct::getLastUpdateUser, model.getLastUpdateUser())
      .set(SupplierOrderProduct::getSku, model.getSku())
      .set(SupplierOrderProduct::getProductName, model.getProductName())
      .set(SupplierOrderProduct::getTag, model.getTag())
      .set(SupplierOrderProduct::getModel, model.getModel())
      .set(SupplierOrderProduct::getApplicationNum, model.getApplicationNum())
      .set(SupplierOrderProduct::getTaxPrice, model.getTaxPrice())
      .set(SupplierOrderProduct::getUnitPrice, model.getUnitPrice())
      .set(SupplierOrderProduct::getCostPrice, model.getCostPrice())
      .set(SupplierOrderProduct::getMainUnitPrice, model.getMainUnitPrice())
      .set(SupplierOrderProduct::getGramWeight, model.getGramWeight())
      .set(SupplierOrderProduct::getLaborCosts, model.getLaborCosts())
      .set(
        SupplierOrderProduct::getAccessoriesPrice,
        model.getAccessoriesPrice()
      )
      .set(SupplierOrderProduct::getTaxRate, model.getTaxRate())
      .set(SupplierOrderProduct::getTaxAmount, model.getTaxAmount())
      .set(SupplierOrderProduct::getTotalPrice, model.getTotalPrice())
      .set(SupplierOrderProduct::getAmount, model.getAmount())
      .set(
        SupplierOrderProduct::getQuantityReceived,
        model.getQuantityReceived()
      )
      .set(SupplierOrderProduct::getQuantityReceive, model.getQuantityReceive())
      .set(SupplierOrderProduct::getQuantityReturn, model.getQuantityReturn())
      .set(
        SupplierOrderProduct::getEndDifferenceQuantity,
        model.getEndDifferenceQuantity()
      )
      .set(
        SupplierOrderProduct::getExpectArriveTime,
        model.getExpectArriveTime()
      )
      .set(SupplierOrderProduct::getArrivalDate, model.getArrivalDate())
      .set(SupplierOrderProduct::getApplicationUnit, model.getApplicationUnit())
      .set(SupplierOrderProduct::getInventoryUnit, model.getInventoryUnit())
      .set(
        model.getPicUrl() != null,
        SupplierOrderProduct::getPicUrl,
        JSON.toJSONString(model.getPicUrl())
      )
      .setSql(model.getPicUrl() == null, "pic_url = null")
      .set(SupplierOrderProduct::getRemarks, model.getRemarks())
      .eq(SupplierOrderProduct::getId, model.getId())
      .update();
    if (isOk) {}
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(
    SupplierOrderProductSearchParamPo search
  ) {
    return false;
  }

  /**
   * 删除供应商订单子表
   * @param id 供应商订单子表的主键
   * @return 删除是否成功
   */
  @Override
  public boolean delete(Long id) throws Exception {
    return this.removeById(id);
  }

  /**
   * 批量删除供应商订单子表
   * @param ids 供应商订单子表的主键列表
   * @return 删除是否成功
   */
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<SupplierOrderProductImportPo> excelToImportRow(
    SupplierOrderProductImportPo row,
    Integer rowNumber,
    SupplierOrderProductVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<SupplierOrderProductImportPo> ir =
      new ImportRow<SupplierOrderProductImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<SupplierOrderProductImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new SupplierOrderProductVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, SupplierOrderProductImportPo.class);

    // 一般数据处理
    if (StringUtils.hasText(row.getBusinessIdent())) {
      vo.setBusinessIdent(
        SupplierOrderProductBusinessIdentEnums.toValue(row.getBusinessIdent())
      );
      if (vo.getBusinessIdent() == null) {
        ir.addError(
          "businessIdent",
          "业务标识只能是：“已变更”, “已退货”, “已换货”"
        );
      }
    }
    vo.setApplicationNum(SheetUtils.tryToInteger(row.getApplicationNum()));
    vo.setTaxPrice(SheetUtils.tryToDecimal(row.getTaxPrice()));
    vo.setUnitPrice(SheetUtils.tryToDecimal(row.getUnitPrice()));
    vo.setCostPrice(SheetUtils.tryToDecimal(row.getCostPrice()));
    vo.setMainUnitPrice(SheetUtils.tryToDecimal(row.getMainUnitPrice()));
    vo.setGramWeight(SheetUtils.tryToDecimal(row.getGramWeight()));
    vo.setLaborCosts(SheetUtils.tryToDecimal(row.getLaborCosts()));
    vo.setAccessoriesPrice(SheetUtils.tryToDecimal(row.getAccessoriesPrice()));
    vo.setTaxRate(SheetUtils.tryToDecimal(row.getTaxRate()));
    vo.setTaxAmount(SheetUtils.tryToDecimal(row.getTaxAmount()));
    vo.setTotalPrice(SheetUtils.tryToDecimal(row.getTotalPrice()));
    vo.setAmount(SheetUtils.tryToDecimal(row.getAmount()));
    vo.setQuantityReceived(SheetUtils.tryToInteger(row.getQuantityReceived()));
    vo.setQuantityReceive(SheetUtils.tryToInteger(row.getQuantityReceive()));
    vo.setQuantityReturn(SheetUtils.tryToInteger(row.getQuantityReturn()));
    vo.setEndDifferenceQuantity(
      SheetUtils.tryToInteger(row.getEndDifferenceQuantity())
    );
    vo.setExpectArriveTime(SheetUtils.tryToDateTime(row.getExpectArriveTime()));
    vo.setArrivalDate(SheetUtils.tryToDate(row.getArrivalDate()));
    SheetUtils.datePreviewFormat(row.getArrivalDate(), row::setArrivalDate);
    // 处理关联字段“产品”
    if (
      !SheetUtils.isBlank(row.getProductIdName()) &&
      SheetUtils.isBlank(row.getProductId())
    ) {
      ProductSearchParamPo productIdSearchParam = new ProductSearchParamPo();
      productIdSearchParam.setLimit(2); // 最大只返回二行记录
      productIdSearchParam.setNameEq(SheetUtils.trim(row.getProductIdName()));
      productIdSearchParam.applySqlSegments();
      List<ProductItemVo> productIdMatches = productMapper.search(
        productIdSearchParam
      );
      if (productIdMatches.size() == 0) {
        ir.addError("productIdName", "未能在产品管理中找到匹配的数据");
      } else if (productIdMatches.size() > 1) {
        ir.addError(
          "productIdName",
          "关联不唯一，在产品管理中找到多个匹配的数据"
        );
      } else {
        vo.setProductId(productIdMatches.get(0).getId());
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<SupplierOrderProductImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<SupplierOrderProductImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            SupplierOrderProductImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              SupplierOrderProductImportPo row,
              AnalysisContext cxt
            ) {
              SupplierOrderProductVo vo = new SupplierOrderProductVo();
              ImportRow<SupplierOrderProductImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<SupplierOrderProductImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<SupplierOrderProductImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      SupplierOrderProductVo vo = new SupplierOrderProductVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @Override
  public void export(
    Long templateId,
    SupplierOrderProductSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "parentSupplierOrder",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              (
                (SupplierOrderProductItemVo) r
              ).getParentSupplierOrderSupplierOrder()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "arrivalDate",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> DateUtils.toDateString((Date) o))
      );
      exportOptions.addStringFields(
        "parentSupplierOrderSupplierOrder",
        "supplierOrderId",
        "sku",
        "productName",
        "tag",
        "model",
        "applicationUnit",
        "inventoryUnit",
        "remarks"
      );

      String fileName = String.format(
        "供应商订单子表(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<SupplierOrderProductExcelPo> items =
      new ArrayList<SupplierOrderProductExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<SupplierOrderProductItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<SupplierOrderProductItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (SupplierOrderProductItemVo item : list) {
        SupplierOrderProductExcelPo excel = new SupplierOrderProductExcelPo();
        BeanUtils.copyProperties(item, excel);

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "供应商订单子表(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(SupplierOrderProductExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过所属供应商订单查询供应商订单子表主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdBySupplierOrderId(String supplierOrderId) {
    return this.baseMapper.getIdBySupplierOrderId(supplierOrderId);
  }

  /**
   * 通过所属供应商订单查询供应商订单子表多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsBySupplierOrderId(List<String> list) {
    return this.baseMapper.getIdsBySupplierOrderId(list);
  }

  /**
   * 通过供应商订单子表主键查询所属供应商订单
   */
  @Override
  public String getSupplierOrderIdById(Long id) {
    return this.baseMapper.getSupplierOrderIdById(id);
  }

  /**
   * 通过供应商订单子表主键查询所属供应商订单列表
   */
  @Override
  public List<String> getSupplierOrderIdByIds(List<Long> ids) {
    List<Map<String, Object>> maps =
      this.baseMapper.getSupplierOrderIdByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap ->
            (String) stringObjectMap.get("supplierOrderId")
          )
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 供应商订单子表的主键
   */
  @Override
  public SupplierOrderProductVo getVoById(Long id) throws Exception {
    SupplierOrderProductVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }
    return vo;
  }

  /**
   * 分页查询供应商订单子表
   * @param search 查询条件
   * @return 供应商订单子表分页查询结果
   */
  @Override
  public Page<SupplierOrderProductItemVo> pageSearch(
    SupplierOrderProductSearchParamPo search
  ) {
    Page<SupplierOrderProductItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(SupplierOrderProductItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 供应商订单子表快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'SupplierOrderProductOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<SupplierOrderProductItemVo>> searchOptions(
    SupplierOrderProductSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询供应商订单子表
   * @param search 查询条件
   * @return 供应商订单子表列表查询结果
   */
  @Override
  public List<SupplierOrderProductItemVo> search(
    SupplierOrderProductSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询供应商订单子表最后更新时间
   * @param search 查询条件
   * @return 供应商订单子表最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(SupplierOrderProductSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }
}
